import model.model as ut
from utils.common.db_connection import db, or_, and_


def query_by_user_id(cur_user_id: int):
    """
    通过user_id查询制单和接单的数据
    :param cur_user_id: 用户id
    :return:
    """
    query = db.session.query(ut.WorkOrder).filter(or_(ut.WorkOrder.make_user_id == cur_user_id,
                                                      ut.WorkOrder.get_user_id == cur_user_id))
    total_count = query.count()
    return total_count


def query_work_order_by_id(id: int) -> ut.WorkOrder:
    """
    通过工单id查询工单详情
    :param id:  工单id
    :return:  工单详情
    """
    item = db.session.query(ut.WorkOrder).filter_by(id=id).first()
    return item


def query_by_link(link: str) -> ut.WorkOrder:
    """
    通过链接查询
    :return:  工单详情
    """
    return db.session.query(ut.WorkOrder).filter_by(link=link).order_by(ut.WorkOrder.ordered_time.desc()).first()


def query_work_order_by_order_id(order_id: int) -> ut.WorkOrder:
    """
    通过工单id查询工单详情
    :param order_id:  工单id
    :return:  工单详情
    """
    item = db.session.query(ut.WorkOrder).filter_by(order_id=order_id).first()
    return item


def modify_work_order_status_and_get_user_id(id: int, cur_status: int, cur_user_id: int) -> ut.WorkOrder:
    """
    修改工单状态
    :param id:
    :param cur_status:
    :param cur_user_id:
    :return:
    """
    item = ut.WorkOrder.query.get(id)
    if item:
        item.status = cur_status
        item.get_user_id = cur_user_id
        db.session.commit()
    return item


def modify_work_order_status(id: int, cur_status: int) -> ut.WorkOrder:
    """
    修改工单状态
    :param id:
    :param cur_status:
    :return:
    """
    item = ut.WorkOrder.query.get(id)
    if item:
        item.status = cur_status
        db.session.add(item)
        db.session.commit()
    return item


def modify_work_order(obj: ut.WorkOrder) -> ut.WorkOrder:
    db.session.add(obj)
    db.session.commit()
    return obj


def modify_work_order_link(id: int, link: str) -> ut.WorkOrder:
    """
    修改工单链接
    :param link:
    :param id:
    :return:
    """
    item = ut.WorkOrder.query.get(id)
    if item:
        item.link = link
        db.session.commit()
    return item


def modify_work_order_feedback(id: int, feedback: str) -> ut.WorkOrder:
    """
    修改工单链接
    :param feedback:
    :param id:
    :return:
    """
    item = ut.WorkOrder.query.get(id)
    if item:
        item.feedback = feedback
        db.session.commit()
    return item


def batch_insert(obj: [ut.WorkOrder]):
    # 批量提交
    db.session.add_all(obj)
    db.session.commit()


def commit_obj(obj: ut.WorkOrder):
    db.session.add(obj)
    db.session.commit()
